#include "widget.h"
#include "ui_widget.h"
#include <QList>

#ifdef Q_CC_MSVC
#include <windows.h>
#include <qwindowdefs_win.h>
#pragma comment(lib, "user32.lib")

//#if _MSC_VER >= 1600
//#pragma execution_character_set(“utf-8”)
//#endif

#endif

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    m_pPicture(new PictureDB),
    m_pTimer(new QTimer),
    m_pTrayicon(new SystemTrayIcon),
    m_pParaSetting(new ParaSettingDB)
{
    ui->setupUi(this);

    //setWindowOpacity(0.8);
    //setWindowFlags(Qt::FramelessWindowHint);
    //setAttribute(Qt::WA_TranslucentBackground);
	//setWallPaper("I:\\my-tools\\wallpaper\\test.jpg");

    //获取数据库数据
    m_pList = m_pPicture->getPath();

    // init
    Model *model = NULL;
    model = m_pParaSetting->getModel();

    if (model == NULL)
    {
        qDebug() << "get model error!";
        Q_ASSERT(false);
    }

    //初始化默认切换时间为10秒
    ui->TimeLineEdit->setText(model->strTime);
    ui->UnitComboBox->setCurrentText(model->strTimeUnit);
    ui->RandomPlayCheckBox->setChecked(model->bShuffle);

    //创建QIcon对象，参数是图标资源，值为项目的资源文件中图标的地址
    QIcon icon(":/御坂美琴.ico");
    this->setWindowIcon(icon);

    //启动计时器
    m_pTimer->setInterval(converteUnit(model->strTime));
    if (model->bStart)
    {
        ui->PlayPushButton->setText(tr("停止"));
        m_pTimer->start();
    }
    else
    {
        ui->PlayPushButton->setText(tr("播放"));
        m_pTimer->stop();
    }

    //初始化开机启动选项
    //ui->AutoStartCheckBox->setChecked(model->bAuto);
    //OnAutoStart(model->bAuto);

	auto nextAction = new QAction("Next", m_pTrayicon);
	auto trayiconMenu = m_pTrayicon->contextMenu();
	auto actions = trayiconMenu->actions();
	actions.prepend(nextAction);
	trayiconMenu->addActions(actions);

    connect( m_pTimer, SIGNAL(timeout()), this, SLOT(timeOutSlot()));
    connect( m_pPicture, SIGNAL(finished()), this, SLOT(searchFinshed()));
    connect( m_pTrayicon, SIGNAL(showMaximized()), this, SLOT(showMaximized()));
    connect( m_pTrayicon, SIGNAL(showNormal()), this, SLOT(showNormal()));
    connect( m_pTrayicon, SIGNAL(showMinimized()), this, SLOT(showMinimized()));
	connect( nextAction, SIGNAL(triggered()), this, SLOT(onChangeWallPaper()));
    //为系统托盘绑定单击信号的槽,即图标激活时
    connect( m_pTrayicon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
             this, SLOT(systemTrayIcon(QSystemTrayIcon::ActivationReason)));

    connect( this, SIGNAL(updateModel()), m_pParaSetting, SLOT(updateModel()));

    // UI event message
    //connect(ui->AutoStartCheckBox, SIGNAL(clicked(bool)), this, SLOT(OnAutoStart(bool)));
    connect(ui->ChangeWallpaperPushButton, SIGNAL(clicked()), this, SLOT(onChangeWallPaper()));
    connect(ui->ExitPushButton, SIGNAL(clicked()), this, SLOT(onExit()));
    connect(ui->LookUpPushButton, SIGNAL(clicked()), this, SLOT(onLookUp()));
    connect(ui->PlayPushButton, SIGNAL(clicked()), this, SLOT(onPlay()));
    connect(ui->TimeLineEdit, SIGNAL(textChanged(QString)), this, SLOT(onTimeChanged(QString)));
    connect(ui->UnitComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onUnitChanged(int)));
    connect(ui->SaveSettingPushButton, SIGNAL(clicked()), this, SLOT(onSaveSetting()));
}

Widget::~Widget()
{
    delete m_pPicture;
    delete m_pParaSetting;
    delete m_pTimer;
    delete m_pList;
    delete m_pTrayicon;
    delete ui;
}

//定时触发处理
void Widget::timeOutSlot()
{
    static int num = 0;

    if ( m_pList->isEmpty())
    {
        qDebug() << "list is Empty!";
        return;
    }

    if ( num > ( m_pList->size() - 1))
        num = 0;

    if (ui->RandomPlayCheckBox->checkState() == Qt::Checked)
    {
        QTime curTime = QTime::currentTime();
        qsrand(curTime.msec() + curTime.second()*1000);
        num = qrand() % (m_pList->size() - 1);

        if ( ! this->setWallPaper( m_pList->at(num)))
        {
            m_pPicture->remove(m_pList->at(num));
        }
    }
    else
    {
        if ( ! this->setWallPaper( m_pList->at(num)))
        {
            m_pPicture->remove(m_pList->at(num));
        }

        num++;
    }
}

void Widget::searchFinshed()
{
    ui->LookUpPushButton->setEnabled(true);
}

//设置壁纸
bool Widget::setWallPaper(const QString &src)
{
    // 转换成宽字节，很重要，否则显示不了图片
	wchar_t path[_MAX_PATH] = { 0 };
	auto ptch = src.toWCharArray(path);
    //WCHAR *ptch = (WCHAR *)src.toStdWString().c_str();
	//WCHAR* ptch = reinterpret_cast<WCHAR *>(src.utf16());
    if ( ! ::SystemParametersInfoW(
             SPI_SETDESKWALLPAPER,
             0,
			 (PVOID)path,
             SPIF_UPDATEINIFILE |
             SPIF_SENDWININICHANGE
             )
         )
    {
        qDebug(src.toStdString().c_str());
        return false;
    }

    return true;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    m_Pos = event->pos();
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - m_Pos);
}

void Widget::onAutoStart(bool bAutoStart)
{
    QString strAppName = QApplication::applicationName();
    QSettings *settings = new QSettings(g_strRegAutoStart, QSettings::NativeFormat);

    if(bAutoStart)
    {
        QString strAppPath = QApplication::applicationFilePath();
        settings->setValue(strAppName, strAppPath.replace("/", "\\"));
    }
    else
    {
        settings->remove(strAppName);
    }
    delete settings;
}

//查找文件并存入数据库
void Widget::onLookUp()
{
    ui->LookUpPushButton->setEnabled(false);
    m_pPicture->searchFile( QFileDialog::getExistingDirectory(this));
}

//开始更换壁纸
void Widget::onPlay()
{
    if ( ! m_pTimer->isActive())
    {
        if ( ! m_pList->isEmpty())
        {
            m_pTimer->start();
            ui->PlayPushButton->setText(tr("停止"));
        }
    }
    else
    {
        m_pTimer->stop();
        ui->PlayPushButton->setText(tr("播放"));
    }
}

//设置壁纸切换时间
void Widget::onTimeChanged(const QString &num)
{
    m_pTimer->setInterval( converteUnit(num));
}

//处理切换时间
int Widget::converteUnit(const QString &num)
{
    static int time = 1000;
    switch (ui->UnitComboBox->currentIndex())
    {
    case 0://秒
        time = num.toInt() * 1000;
        break;
    case 1://分
        time = 60 * (num.toInt() * 1000);
        break;
    case 2://小时
        time = 60 * (60 * (num.toInt() * 1000));
        break;
    case 3://天
        time = 24 * ( 60 * (60 * (num.toInt() * 1000)));
        break;
    default:
        break;
    }
    return time;
}

//切换时间单位处理
void Widget::onUnitChanged(int)
{
    onTimeChanged(ui->TimeLineEdit->text());
}

//系统托盘化
void Widget::systemTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
        //添加自己处理
        break;
    case QSystemTrayIcon::DoubleClick:
        //双击回复
        this->setWindowState(Qt::WindowActive);
        this->show();
        break;
    case QSystemTrayIcon::MiddleClick:
        //添加自己处理
        break;
    default:
        break;
    }
}

//重载关闭事件
void Widget::closeEvent(QCloseEvent *e)
{
    if( m_pTrayicon->isVisible())
    {
        hide();
        e->ignore();
    }
}

void Widget::onSaveSetting()
{
    Model* model = NULL;
    model = m_pParaSetting->getModel();
    if (model == NULL)
    {
        Q_ASSERT(false);
    }

    model->strTime = ui->TimeLineEdit->text();
    model->strTimeUnit = ui->UnitComboBox->currentText();
    model->bShuffle = ui->RandomPlayCheckBox->isChecked();
    model->bStart = m_pTimer->isActive();
    model->bAuto = ui->AutoStartCheckBox->isChecked();

    emit updateModel();
}

void Widget::onChangeWallPaper()
{
    timeOutSlot();
    if (m_pTimer->isActive())
    {
        m_pTimer->start();
    }
}

void Widget::onExit()
{
    qApp->quit();
}
